<template>
	<view class="sign">
		<view style="width: 100%;
				display: flex;
				height: 0;
				flex: 1;" class="content">
			<!-- 合同内容 -->
			<scroll-view style="width: 100%;height: 100%;" scroll-y @scroll="onScroll">
				<image v-for="item in imageList" :key="item.name" :src="item.url" style="width: 100%;"
					:style="{ height: `${pdfShowHeight}px`}">
				</image>
				<!-- 印章 -->
				<image style="position: absolute;" class="sign-select" v-if="selectContract && !isQiFeng"
					:src="selectContract.url"
					:style="{top: imgTop + 'px', left: imgLeft + 'px', width: imgWidth + 'px', height: imgWidth + 'px'}"
					@touchstart.stop.prevent="handleTouchStart" @touchmove.stop.prevent="handleTouchMove"
					@touchend="handleTouchEnd"></image>
			</scroll-view>

			<view v-if="selectContract && isQiFeng" :style="{width: qifengContainerWidth + 'px'}"
				style="position: absolute;top: 0;right: 0;height: calc(100% - 65px);border: 2px dashed #007aff;"></view>
			<!-- 印章 -->
			<image style="position: absolute;" class="sign-select" v-if="selectContract && isQiFeng"
				:src="selectContract.url"
				:style="{top: imgTop + 'px', left: imgLeft + 'px', width: imgWidth + 'px', height: imgWidth + 'px'}"
				@touchstart.stop.prevent="handleTouchStart" @touchmove.stop.prevent="handleTouchMove"
				@touchend="handleTouchEnd"></image>
		</view>
		<view class="sign-toolbar">
			<view class="sign-toolbar-menu sign-toolbar-menu-border" @click="() => {
				isQiFeng = false
				$refs.alertDialog.open()
			}">
				<text>盖章</text>
			</view>
			<view class="sign-toolbar-menu sign-toolbar-menu-border" @click="() => {
				isQiFeng = true
				$refs.alertDialog.open()
			}">
				<text>盖骑缝章</text>
			</view>
			<view class="sign-toolbar-menu sign-toolbar-menu-border" @click="onSign">
				<text class="sign-toolbar-menu">签署</text>
			</view>
		</view>

		<uni-popup ref="alertDialog" type="dialog">
			<uni-popup-dialog type="" cancelText="取消" confirmText="确认" title="印章选择" @confirm="alertDialogConfirm"
				@close="">
				<scroll-view scroll-y>
					<view style="display: flex;align-items: center;margin-top: 20px;" v-for="item in contractList"
						:key="item.fileName" @click="onSelectContract(item)">
						<text style="display: flex;flex: 1;margin-right: 10px;">{{ item.fileName }}</text>
						<image style="width: 80px;height: 80px;margin-right: 30px;" :src="item.url"></image>
						<!-- <image style="width: 20px;height: 20px;"
							:src="(preSelectContract && preSelectContract.id == item.id) ? '' : ''"></image> -->
						<radio :checked="preSelectContract?.url == item.url" @click="onSelectContract(item)" />
					</view>
				</scroll-view>
			</uni-popup-dialog>
		</uni-popup>

		<uni-popup ref="msgSignDialog" type="dialog" class="psw-popup">
			<uni-popup-dialog type="" cancelText="取消" confirmText="确认" @confirm="dialogConfirm"
				@close="preSelectContract = selectContract">
				<view style="display: flex;flex-direction: column;align-items: center;">
					<view style="display: flex;">
						<text :style="{ 'color': currentTab == 0 ? '#007aff' : ''}" @click="currentTab = 0">短信签署</text>
						<text style="margin-left: 20px;" :style="{ 'color': currentTab == 1 ? '#007aff' : ''}"
							@click="currentTab = 1">密码签署</text>
					</view>
					<view v-if="currentTab == 0">
						<view style="display: flex;margin-top: 30px;width: 100%;">
							<text>{{ `手机号：${sealData.mobile}`}}</text>
							<text style="margin-left: 10px;flex: 1;"></text>
						</view>
						<view style="display: flex;margin-top: 20px;width: 100%;align-items: center;">
							<text>验证码：</text>
							<input style="margin-left: 10px;display: flex;flex: 1;border: 1px solid lightgray;"
								v-model="msg" type="number"></input>
							<button @click="onSendMsg" :disabled="sendMsgDisabled"
								style="margin-left: 10px;color: white;background-color: #007aff;font-size: 13px;padding-left: 5px;padding-right: 5px;">{{ sendMsgTitle }}</button>
						</view>
					</view>
					<view v-else-if="currentTab == 1" style="margin-top: 20px;">
						<text v-if="!sealData.hasSignPassword">您还未设置签署密码，请到安全中心设置后方可使用。</text>
						<view v-else style="display: flex;width: 100%;align-items: center;">
							<text>密码：</text>
							<input style="margin-left: 10px;display: flex;flex: 1;border: 1px solid lightgray;"
								type="number" v-model="psw"></input>
						</view>
					</view>
				</view>
			</uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script lang="ts">
	import {
		loadPdfFromData
	} from '../../utils/pdf2img'
	import {
		onLoad
	} from "@dcloudio/uni-app"
	import {
		http
	} from '../../api/request';

	export default {
		// props: {
		// 	workId: {
		// 		type: String,
		// 		default: "338fa3e9-7d32-4dd7-9af4-f3a901809d9b",
		// 	},
		// 	attachmentId: {
		// 		type: String,
		// 		default: "51328327-e207-4f64-9d60-ed7e93f75383",
		// 	},
		// },
		data() {
			return {
				workId: '',
				attachmentId: '',
				contractList: [],
				selectContract: null,
				preSelectContract: null,
				currentTab: 0,
				imgTop: 0,
				imgLeft: 0,
				imgWidth: 80,
				startX: 0,
				startY: 0,
				isDragging: false,
				signParentWidth: 0,
				signParentHeight: 0,
				pdfShowHeight: 0,
				isQiFeng: false,
				qifengContainerWidth: 100,
				imageList: [],
				sendMsgTitle: '发送验证码',
				sendMsgDisabled: false,
				timer: null,
				timerCount: 60,
				msg: '',
				psw: '',
				scrollTop: 0,
				// 用印文件信息
				attachment: {
					name: '',
				},
				// 印章数据
				sealData: {
					hasSignPassword: false,
					mobile: '',
				},
				pdfWidth: 0,
				pdfHeight: 0,
				sealWidth: 0,
			}
		},
		onReady() {
			this.getParentWidth();
		},
		onLoad() {
			this.workId = this.FGetQueryParam('workId')
			this.attachmentId = this.FGetQueryParam('attachmentId')
			http.get(`/x_processplatform_assemble_surface/jaxrs/attachment/download/${this.attachmentId}`,
				{
					responseType: 'arraybuffer'
				}).then(resp => {
					let th = this
					loadPdfFromData(resp, function (data, pdfWidth, pdfHeight) {
						th.imageList = data
						th.pdfWidth = pdfWidth
						th.pdfHeight = pdfHeight
						th.imgWidth = th.sealWidth * th.signParentWidth / th.pdfWidth
						th.pdfShowHeight = th.signParentWidth * th.pdfHeight / th.pdfWidth
					});
				})
			this.getSealList()
		},
		methods: {
			FGetQueryParam(key : string) {
				const reg = new RegExp('(^|&)' + key + '=([^&]*)(&|$)', 'i');
				const match = window.location.search.substring(1).match(reg) ?? '';
				if (match.length > 2) {
					return decodeURIComponent(match[2]);
				}
			},
			onSign() {
				if (!this.selectContract) {
					uni.showToast({
						title: '请先选择印章',
						icon: 'error'
					})
					return
				}
				this.$refs.msgSignDialog.open()
			},
			onScroll(event) {
				const { scrollLeft, scrollTop, scrollHeight, scrollWidth, deltaX, deltaY } = event.detail
				this.scrollTop = scrollTop
			},
			async onSendMsg() {
				const resp = await http.post(
					`/t_certificate_assemble_control/jaxrs/certificate/business/sendSMSCode`)
				if (resp.type === "success") {
					uni.showToast({
						title: resp.message
					})
					// 倒计时
					this.sendMsgDisabled = true
					var th = this
					this.timer = setInterval(() => {
						th.timerCount--
						th.sendMsgTitle = `${th.timerCount}s`
						if (th.timerCount <= 0) {
							clearInterval(th.timer);
							th.timer = null;
							th.timerCount = 60
							th.sendMsgTitle = `发送验证码`
							th.sendMsgDisabled = false
						}
					}, 1000);
				}
			},
			async getSealList() {
				const resp = await http.get(
					`/t_certificate_assemble_control/jaxrs/certificate/seal/${this.workId}/${this.attachmentId}`)
				if (resp.type === "success") {
					const sealFiles = resp.data.sealFiles ?? [];
					sealFiles.forEach(async (seal) => {
						const resp1 = await http.get(
							`/x_cms_assemble_control/jaxrs/fileinfo/download/document/${seal.attachment}?fileName=${seal.fileName}`,
							{
								responseType: 'arraybuffer'
							}
						)
						let blob = new Blob([resp1])
						var url = URL.createObjectURL(blob);
						this.contractList.push({
							...seal,
							url: url,
						});

						// 创建一个Image对象
						const img = new Image();

						// 设置Image对象的src属性为创建的URL
						img.src = url;

						// 等待图片加载完成
						img.onload = () => {
							// 获取图片宽度和高度
							this.sealWidth = img.naturalWidth;
							this.imgWidth = this.sealWidth * this.signParentWidth / this.pdfWidth
						};
					});
					this.sealData = { ...resp.data }
					this.attachment = { ...resp.data.attachment }
				}
			},
			onSelectContract(item) {
				this.preSelectContract = item
			},
			alertDialogConfirm() {
				this.selectContract = this.preSelectContract
				if (this.isQiFeng) {
					this.imgTop = (this.signParentHeight - this.imgWidth) / 2
					this.imgLeft = this.signParentWidth - this.imgWidth - (this.qifengContainerWidth - this.imgWidth) / 2
				} else {
					this.imgTop = 0
					this.imgLeft = 0
				}
			},
			async dialogConfirm() {
				uni.showLoading({
					mask: true
				})
				if (this.currentTab == 0) {
					// 短信签署
					const resp = await http.post(
						`/t_certificate_assemble_control/jaxrs/certificate/business/confirmSMSCode?SMSCode=${this.msg}`)
					if (resp.type === "success") {
						this.confirmSign()
					}
				} else {
					const resp = await http.post(
						`/t_certificate_assemble_control/jaxrs/certificate/business/confirmSignPassword`, {
						signPassword: this.psw
					})
					if (resp.type === "success") {
						this.confirmSign()
					}
				}
			},
			async confirmSign() {
				const query = uni.createSelectorQuery();
				query.select('.sign-select').fields({
					rect: true
				}, async (res) => {
					const pageZero = Math.floor((this.scrollTop + res.top) / this.pdfShowHeight)
					const position = {
						width: this.imgWidth,
						height: this.imgWidth,
						page: pageZero + 1,
						pageWidth: this.signParentWidth,
						pageHeight: this.pdfShowHeight
					}
					const body = {
						signType: this.isQiFeng ? 3 : 1,
						workId: this.workId,
						signFileId: this.attachmentId,
						signFileName: this.attachment.name,
						sealFileId: this.selectContract.attachment,
					}
					if (this.isQiFeng) {
						position.offsetX = res.left - (this.signParentWidth - this.qifengContainerWidth)
						position.offsetY = res.top
						body.sourcePositionProperty = position
						body.pageConfigEnum = 'all'
						body.pageValue = '1'
					} else {
						position.offsetX = res.left
						position.offsetY = res.top + this.scrollTop - (pageZero * this.pdfShowHeight)
						body.positionList = [position]
					}
					const resp = await http.post(
						`/t_certificate_assemble_control/jaxrs/certificate/sign`, body)
					uni.hideLoading()
					if (resp.type === "success") {
						uni.showToast({
							title: '签署成功'
						})
						this.currentTab = 0
						this.psw = ''
						this.msg = ''
						this.selectContract = null
						this.isQiFeng = false
						setTimeout(() => {
							location.reload()
						}, 2000)
					}
				}).exec()

			},
			getParentWidth() {
				const query = uni.createSelectorQuery();
				query.select('.content').fields({
					size: true
				}, (res) => {
					this.signParentWidth = res.width
					this.signParentHeight = res.height
				}).exec()
			},
			handleTouchStart(event) {
				event.stopPropagation();
				this.startX = event.touches[0].pageX;
				this.startY = event.touches[0].pageY;
				this.isDragging = true;
			},
			handleTouchMove(event) {
				if (this.isDragging) {
					const moveX = event.touches[0].pageX - this.startX;
					const moveY = event.touches[0].pageY - this.startY;
					this.imgTop += moveY;
					this.imgLeft += moveX;
					if (this.imgTop < 0) {
						this.imgTop = 0
					}
					if (this.imgLeft + this.imgWidth > this.signParentWidth) {
						this.imgLeft = this.signParentWidth - this.imgWidth
					}
					if (this.isQiFeng) {
						if (this.imgTop + this.imgWidth > this.signParentHeight) {
							this.imgTop = this.signParentHeight - this.imgWidth
						}
						if (this.imgLeft < this.signParentWidth - this.qifengContainerWidth) {
							this.imgLeft = this.signParentWidth - this.qifengContainerWidth
						}
					} else {
						if (this.imgLeft < 0) {
							this.imgLeft = 0
						}
					}
					this.startX = event.touches[0].pageX;
					this.startY = event.touches[0].pageY;
				}
			},
			handleTouchEnd(event) {
				this.isDragging = false;
			}
		}
	}
</script>

<style lang="scss" scoped>
	uni-page-body {
		height: 100%;
	}

	.sign {
		display: flex;
		flex-direction: column;
		height: 100%;

		:deep(.uni-scroll-view-content) {}

		&-toolbar {
			display: flex;
			width: 100%;
			height: 60px;
			box-shadow: 0 -10px 15px -10px rgba(0, 0, 0, 0.5);
			align-items: center;
			z-index: 99999;

			&-menu {
				display: flex;
				flex: 1;
				height: 50%;
				color: #007aff;
				align-items: center;
				justify-content: center;
			}

			&-menu-border {
				border-right: 1px solid lightblue;
			}
		}


	}

	.psw-popup {
		:deep(.uni-dialog-title) {
			display: none;
		}
	}
</style>